package xyz.paragon.product.persistence.service.impl;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import xyz.paragon.product.persistence.domain.Product;
import xyz.paragon.product.persistence.repository.ProductRepository;
import xyz.paragon.product.persistence.service.ProductService;
import xyz.paragon.product.persistence.service.specification.ProductSpecifications;

import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {

    private final ProductRepository productRepository;

    public ProductServiceImpl(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @Override
    public List<Product> findAll(Map<String, String> params) {
        Specification<Product> productSpecifications = ProductSpecifications.createProductSpecifications(params);
        return this.productRepository.findAll(productSpecifications);
    }

    @Override
    public Product findById(Long productId) {
        return this.productRepository.findById(productId).orElseThrow(EntityNotFoundException::new);
    }

    @Override
    public Product save(Product newProduct) {
        return this.productRepository.save(newProduct);
    }

    @Override
    public void deleteById(Long productId) {
        this.productRepository.deleteById(productId);
    }

}
